package cn.edu.gdgm.system.controller;

import cn.edu.gdgm.system.dto.Result;
import cn.edu.gdgm.system.entity.Device;
import cn.edu.gdgm.system.service.IDeviceService;
import cn.fightingguys.security.web.wechat.entity.WeChatMiniProgramUserDetails;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author quan
 * @date 2021-03-06
 */
@Api(tags = {"药盒设备Controller"})
@RestController
@RequestMapping("/device")
public class DeviceController {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Resource
    private IDeviceService deviceService;


    @PostMapping("/scan")
    @PreAuthorize("hasAuthority('Verified')")
    @ApiOperation(value = "扫描添加药盒")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uuid", value = "设备UUID唯一识别号"),
    })
    public Result scan(@RequestParam String uuid, @ApiIgnore @AuthenticationPrincipal WeChatMiniProgramUserDetails userDetails) {
        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userDetails.getOpenId());
        int count = deviceService.count(queryWrapper) + 1;
        Device device = new Device();
        device.setUuid(uuid);
        device.setUserId(userDetails.getOpenId());
        device.setFirstLaunchTime(LocalDateTime.now());
        device.setRemark(count + "号药盒");
        return toResult(deviceService.save(device));
    }

    @GetMapping()
    @PreAuthorize("hasAuthority('Verified')")
    @ApiOperation(value = "查看当前用户所有药盒（以添加时间排序）")
    public Result list(@ApiIgnore @AuthenticationPrincipal WeChatMiniProgramUserDetails userDetails) {
        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userDetails.getOpenId());
        queryWrapper.orderByAsc("first_launch_time");
        List<Device> data = deviceService.list(queryWrapper);
        return Result.success(data);
    }

    @DeleteMapping()
    @PreAuthorize("hasAuthority('Verified')")
    @ApiOperation(value = "删除药盒")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uuid", value = "设备UUID唯一识别号"),
    })
    public Result delete(@RequestParam String uuid, @ApiIgnore @AuthenticationPrincipal WeChatMiniProgramUserDetails userDetails) {
        boolean rs = deviceService.removeById(uuid);
        return toResult(rs);
    }

    private Result toResult(boolean b) {
        if (b) {
            return Result.success("操作成功");
        } else {
            return Result.error(201, "操作失败");
        }
    }
}
